import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Tabs, Card, Pagination, Row, Col, Modal } from 'antd';

const confirm = Modal.confirm;
import { toJS } from 'mobx';
import { WeaTableNew, WeaSwitch } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { WeaRightMenu, WeaTop, WeaTab, WeaErrorPage, WeaBrowser, WeaTools, WeaProgress, WeaAlertPage, WeaFormItem, WeaSearchGroup } from 'ecCom';
import { locale } from 'moment';
import InstockAdd from './InstockAdd';
import HistoryInstock from './HistoryInstock';
import { Condition, getAdButtons } from '../list/listCondition';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

@inject('cptInstockStore')
@observer
class Instock extends React.Component {
  constructor(props) {
    super(props);
  }
  componentWillMount() {
    const { cptInstockStore } = this.props;
    cptInstockStore.clearStatus();
  }
  componentDidMount() {
    this.doInit(this.props);
  }
  doInit(props) {
    const { location, cptInstockStore } = props;
    const { initDatas } = cptInstockStore;
    initDatas();
  }
  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      const { location, cptInstockStore } = nextProps;
      const { initDatas } = cptInstockStore;
      cptInstockStore.clearStatus();
      initDatas();
    }
  }
  componentWillUnmount() {
    const { cptInstockStore } = this.props;
    cptInstockStore.clearStatus();
  }
  render() {
    const { cptInstockStore, location } = this.props;
    const { loading, tableStore, showSearchAd, showBatchSubmit, form, searchParams, hasRight, verified } = cptInstockStore;
    const { initDatas, doSearch } = cptInstockStore;
    const formParams = form.getFormParams() || {};
    const title = getLabel(15306, '入库申请');
    const topTab = [
      { title: getLabel(83688, '填写入库单'), key: '0' },
      { title: getLabel(84363, '历史申请记录'), key: '1' },
    ];


    if (verified && !hasRight) {
      return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@cuycov`} >
        <div style={{ color: '#000' }}>
          {getLabel(2012, '对不起，您暂时没有权限！')}
        </div>
      </WeaAlertPage>
      );
    }
    if (verified && hasRight) {
      return (
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@hvmhyq`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)} >
          <WeaTop
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@1h8yuo`}
            title={title}
            loading={loading}
            icon={<i className="icon-coms-fa" />}
            iconBgcolor="#f14a2d"
            buttons={this.getTopButtons()}
            buttonSpace={10}
            showDropIcon
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick.bind(this)}
          >
            <WeaTab
              ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@4zup7n`}
              datas={topTab}
              keyParam="key" // 主键
              selectedKey={searchParams.tabkey}
              buttonsAd={searchParams.tabkey == '1' && getAdButtons(cptInstockStore)}
              searchType={searchParams.tabkey == '1' && ['advanced']}
              searchsBaseValue={formParams.prjname}
              setShowSearchAd={(bool) => { cptInstockStore.setShowSearchAd(bool); }}
              hideSearchAd={() => cptInstockStore.setShowSearchAd(false)}
              searchsAd={
                <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@bphaqr`} listStore={cptInstockStore} form={form} onEnterSearch={this.onEnterSearch} /></div>
              }
              showSearchAd={showSearchAd}
              onChange={(key) => { cptInstockStore.changeTab(key); }}
            />
            {searchParams.tabkey == '0' ? <div>
              {this.getFormFields()}
              <InstockAdd ecId={`${this && this.props && this.props.ecId || ''}_InstockAdd@88y2x5`} />
            </div>
              : <HistoryInstock ecId={`${this && this.props && this.props.ecId || ''}_HistoryInstock@udgiju`} />}
          </WeaTop>
        </WeaRightMenu>);
    }
    return (<div />);
  }

  getFormFields() {
    const { mainTableInfo, addForm } = this.props.cptInstockStore;
    const { isFormInit } = addForm;
    const group = [];
    isFormInit && mainTableInfo.map((c, i) => {
      const items = [];
      c.items.map((fields) => {
        const hide = false;
        items.push({
          com: (<WeaFormItem
            ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@u3qsrp@${fields.domkey[0]}`}
            error={addForm.getError(fields)}
            tipPosition="bottom"
            label={`${fields.label}`}
            labelCol={{ span: `${fields.labelcol}` }}
            wrapperCol={{ span: `${fields.fieldcol}` }}
          >
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ooc3xs@${fields.domkey[0]}`} fieldConfig={fields} form={addForm} />
          </WeaFormItem>),
          colSpan: 1,
          hide,
        });
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@ksx49w@${i}`} needTigger title={c.title} col={2} showGroup={c.defaultshow} items={items} />);
    });
    return group;
  }
  getTopButtons() {
    const { cptInstockStore } = this.props;
    const { searchParams, tableStore, instockInfoStore, ismanager, visible } = cptInstockStore;
    const selectedLen = tableStore.selectedRowKeys.length;
    const btnArr = [];
    const that = this;
    { searchParams.tabkey == '0' && btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jhbz93@submit`} type="primary" disabled={visible} onClick={() => { cptInstockStore.doInstock(); }}>{getLabel(615, '提交') }</Button>); }
    { searchParams.tabkey == '1' && ismanager && btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3aupwl@del`} type="primary" disabled={selectedLen <= 0} onClick={() => { that.batchDeleteClick(); }}>{getLabel(32136, '批量删除') }</Button>); }
    return btnArr;
  }

  getRightMenu() {
    const { cptInstockStore } = this.props;
    const { searchParams, ismanager, tableStore, visible } = cptInstockStore;
    const selectedLen = tableStore.selectedRowKeys.length;
    const btnArr = [];
    {
      searchParams.tabkey == '0' &&
            btnArr.push({
              icon: <i className="icon-coms-Upload-successfully" />,
              content: getLabel(615, '提交'),
              disabled: visible,
              key: '0',
            });
    }
    {
      searchParams.tabkey == '1' && ismanager &&
            btnArr.push({
              icon: <i className="icon-coms-batch" />,
              content: getLabel(32136, '批量删除'),
              disabled: selectedLen <= 0,
              key: '1',
            });
    }
    {
      searchParams.tabkey == '1' &&
            btnArr.push({
              icon: <i className={'icon-coms-Custom'} />,
              content: getLabel(32535, '显示列定制'),
              key: '2',
            });
    }

    	return btnArr;
  }
  onRightMenuClick(key) {
    const { cptInstockStore } = this.props;
    const that = this;
    if (key == '0') { // 提交
      cptInstockStore.doInstock();
    }
    if (key == '1') { //
      that.batchDeleteClick();
    }
    if (key == '2') { //
      cptInstockStore.showColumn();
    }
  }
  reRenderColumns(columns) {
    columns.forEach((c) => {
      if (c.dataIndex == 'finish') {
        c.render = function (text, record) {
          return (<span className="wea-prj-progressStyle" >
            <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@r3xrrr@${c.dataIndex}`} percent={record.finish} strokeColor={record.finishspan} />
          </span>);
        };
      } else {
        c.render = function (text, record) {
          const valueSpan = record[`${c.dataIndex}span`] !== undefined ? record[`${c.dataIndex}span`] : record[c.dataIndex];
          return <span dangerouslySetInnerHTML={{ __html: valueSpan }} />;
        };
      }
    });
    return columns;
  }

    batchDeleteClick = () => { // 批量删除
      const { cptInstockStore } = this.props;
      const { tableStore } = cptInstockStore;
      Modal.confirm({
        title: getLabel(15172, '系统提示'),
        content: getLabel(83692, '您确认要批量处理选中的记录吗？'),
        onOk() {
          cptInstockStore.doDelete({ instockid: tableStore.selectedRowKeys });
        },
        onCancel() { },
      });
    }

    onOperatesClick(record, index, operate, flag) {
      const { cptInstockStore } = this.props;
      const _href = operate && operate.href ? operate.href : '';
      let fn = _href.replace('javascript:', '');
      fn = fn.substring(0, fn.indexOf('('));
      const that = this;
      if (fn != '') {
        if (fn == 'onGiveback') {
          const params = { viewtype: 'cptbackone', capitalid: record.randomFieldId };
          confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel(83559, '您确认要归还吗?'),
            onOk() {
              cptInstockStore.onGiveback(params);
            },
            onCancel() {},
          });
        }
      }
    }

    onEnterSearch = () =>{
      const { cptInstockStore } = this.props;
      cptInstockStore.doSearch();
      cptInstockStore.setShowSearchAd(false);
    }

}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@ozk1ay`} msg={props.error ? props.error : getLabel(383324, '对不起，该页面异常，请联系管理员')} />,
  { error: '' },
)(Instock);
